import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'
import LayoutView from '../views/LayoutView.vue'
import store from '../store'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'layout',
    component: LayoutView,
    children: [
      {
        path: '',
        name: 'home',
        component: HomeView,
        meta: {
          auth: true // 表明该路由需要登录后访问
        }
      },
      {
        path: 'class',
        name: 'class',
        component: () => import('../views/ClassView.vue'),
        meta: {
          auth: true
        }
      },
      {
        path: 'student',
        name: 'student',
        component: () => import('../views/StudentView.vue'),
        meta: {
          auth: true
        }
      },
      {
        path: 'about',
        name: 'about',
        component: () => import('../views/AboutView.vue'),
        meta: {
          auth: true
        }
      },
      {
        path: 'center',
        name: 'cnter',
        component: () => import('../views/UserCenter.vue'),
        meta: {
          auth: true
        }
      },
      {
        path: 'setting',
        name: 'setting',
        component: () => import('../views/SettingView.vue'),
        meta: {
          auth: true
        }
      },
      {
        path: 'role',
        name: 'role',
        component: () => import('../views/AuthRole.vue'),
        meta: {
          auth: true
        }
      }
    ]
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/LoginView.vue')
  },
  {
    path: '/loginkeep',
    name: 'loginkeep',
    component: () => import('../views/LoginKeep.vue')
  },
  {
    path: '*',
    name: 'notfound',
    component: () => import('../views/NotFound.vue')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 路由守卫 - 登录拦截
router.beforeEach((to, from, next) => {
  const token = store.state.user.token; // 表示用户登录的凭证

  if(to.meta.auth) { // 如果路由中的 meta 字段下的 auth 为true，表示该路由必须登录后访问
    if(token) { // token 存在，表示已经登陆了，那么想干嘛干嘛去
      next();
    } else { // 不存在，表明你没有登录，不好意思，回到登录页
      next('/login');
    }
  } else { // 不需要登录就可以访问
    next(); // 直接下一步
  }
})

export default router
